import urllib2
from xml.etree import cElementTree as ElementTree
from urllib import quote_plus
from MultiDict import UnorderedMultiDict
MAL_SEARCH_URL = "http://mal-api.com/anime/search?format=xml&q={query}"
MAL_GET_URL = "http://mal-api.com/anime/{id}?format=xml"
cache = {}
def search_anime(query):
    url = MAL_SEARCH_URL.format(query=quote_plus(query))
    result = urllib2.urlopen(url)
    return ElementTree.parse(result)
def get_anime(aid):
    url = MAL_GET_URL.format(id=int(aid))
    result = urllib2.urlopen(url)
    return ElementTree.parse(result)

def get_anime_picture_link(query=None, aid=None, match=0):
    """Gets the link to a picture for a certain anime.
    
    if ID is specified it uses this to find the anime.
    
    if query is specified it will do a search and return
    'match' match. Default is the first result. If the
    'match' match does not exist default to 0"""
    assert query or aid
    if (aid):
        if (cache.get(aid) != None):
            result = cache.get(aid)
        else:
            result = get_anime(aid)
    elif (query):
        if (cache.get(query) != None):
            result = cache.get(query)
        else:
            result = search_anime(query)
    if (check_empty(result)):
        image_url = result.find("image_url")
        if (image_url != None):
            cache[aid] = result
            return image_url.text
        else:
            image_url = result.findall("anime")
            cache[query] = result
            try:
                image_url = image_url[match]
            except (IndexError):
                image_url = image_url[0]
            return image_url.find("image_url").text
    else:
        #should raise different exceptions here
        pass
    
def check_empty(Element):
    if (Element.getroot().tag == "error"):
        # Error check
        return False
    if (Element.find("title") != None):
        # ID check
        return True
    if (Element.find("count").text != "0"):
        # Search result check
        return True
        